import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import type { Address } from '@/types/address'
// 定义 Store
export const useAddressStore = defineStore(
  'address',
  () => {
    // 地址信息
    const addressList = ref<Address[]>([])
    // 保存地址信息
    const setAddress = (val: Address) => {
      addressList.value = [val, ...addressList.value]
    }
    // 修改默认信息
    const setIsDefaule = () => {
      const find = addressList.value.find((item) => item.isDefault === 1)
      if (find) {
        find.isDefault = 0
      }
    }
    // 删除地址
    const deleteAddress = (index: number) => {
      addressList.value.splice(index, 1)
    }
    // 确认地址
    const isDefaultAddress = computed(() => {
      return addressList.value.find((item) => item.isDefault === 1)?.region
    })
    return {
      addressList,
      setAddress,
      setIsDefaule,
      deleteAddress,
      isDefaultAddress,
    }
  },
  // TODO: 持久化
  {
    persist: {
      storage: {
        getItem(key) {
          return uni.getStorageSync(key)
        },
        setItem(key, value) {
          return uni.setStorageSync(key, value)
        },
      },
    },
  },
)
